<template>
    <div class="detail-container">
        <!-- 标题栏 -->
        <div class="content-header">
            <div class="content-title">
                <span>溯源详情</span>
                <el-button type="primary" size="small" @click="goBack">
                    <el-icon>
                        <Back />
                    </el-icon> 返回
                </el-button>
            </div>
            <div v-if="detailData" class="batch-info">
                <span class="batch-label">当前批次:</span>
                <span class="batch-value">{{ detailData.productionBatch }}</span>
            </div>
        </div>
        <!-- 详情内容 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="10" animated />
        </div>
        <div v-else-if="!detailData" class="error-container">
            <el-empty description="未找到溯源信息" />
        </div>
        <div v-else class="detail-content">
            <!-- 商品基本信息 -->
            <div class="detail-section">
                <h2>{{ detailData.productName }}</h2>
                <div class="product-layout">
                    <!-- 左侧溯源图片 -->
                    <div class="product-image-container">
                        <div class="product-image">
                            <img v-if="detailData.coverImage" :src="detailData.coverImage" alt="商品图片" />
                            <el-empty v-else description="暂无图片" :image-size="150" />
                        </div>
                    </div>
                    <!-- 右侧基本信息和产品检验报告 -->
                    <div class="product-info-container">
                        <!-- 基本信息 -->
                        <div class="product-details">
                            <div class="info-row">
                                <span class="info-label">生产批次：</span>
                                <span class="info-value">{{ detailData.productionBatch }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">保质期：</span>
                                <span class="info-value">{{ detailData.shelfLife }} 天</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">生产许可证号：</span>
                                <span class="info-value">{{ detailData.productionLicense }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">生产企业：</span>
                                <span class="info-value">{{ detailData.manufacturer }}</span>
                            </div>
                        </div>
                        <!-- 产品检验报告 -->
                        <div class="report-section">
                            <h3 class="report-title">产品检验报告</h3>
                            <div class="report-content">
                                <inspection-images :images="inspectionImages" :image-category="currentImageCategory"
                                    @show-upload="showUploadDialog" @delete-image="deleteImage" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 标签页切换不同内容 -->
            <el-tabs class="detail-tabs" v-model="activeTab">
                <el-tab-pane label="养殖信息" name="breeding">
                    <breeding-info-tab :production-batch="detailData?.productionBatch || ''" />
                </el-tab-pane>
                <el-tab-pane label="屠宰信息" name="slaughter">
                    <slaughter-info-tab :production-batch="detailData?.productionBatch || ''" />
                </el-tab-pane>
                <el-tab-pane label="深加工信息" name="processing">
                    <processing-info-tab :production-batch="detailData?.productionBatch || ''" />
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 上传图片对话框 -->
        <el-dialog v-model="uploadDialogVisible" title="上传检验图片" width="500px" align-center destroy-on-close>
            <div class="upload-container">
                <el-upload class="upload-demo" :action="getMultipleUploadUrl" :headers="uploadHeaders" multiple
                    :limit="10" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
                    :on-error="handleUploadError" :before-upload="beforeUpload" :file-list="fileList"
                    list-type="picture-card">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <div class="el-upload__tip">
                    请上传JPG/PNG格式图片，单个文件不超过5MB，最多可上传10张
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="uploadDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmUpload">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Back, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { traceabilityService } from '@/http/traceabilityService'
import { imageService } from '@/http/imageService'
import BreedingInfoTab from '@/components/traceability/BreedingInfoTab.vue'
import SlaughterInfoTab from '@/components/traceability/SlaughterInfoTab.vue'
import ProcessingInfoTab from '@/components/traceability/ProcessingInfoTab.vue'
import InspectionImages from '@/components/traceability/InspectionImages.vue'

// 定义溯源详情数据类型
interface TraceabilityDetail {
    traceabilityId: string
    productName: string
    productionBatch: string
    shelfLife: string
    productionLicense: string
    manufacturer: string
    coverImage: string
    createdBy?: string
    createdTime?: string
    lastModifiedBy?: string
    lastModifiedTime?: string
}

const route = useRoute()
const router = useRouter()
const loading = ref(true)
const detailData = ref<TraceabilityDetail | null>(null)
const activeTab = ref('breeding') // 默认选择养殖信息标签

// 产品检验图片相关
const inspectionImages = ref<{ url: string; uid: string }[]>([])
const uploadDialogVisible = ref(false)
const fileList = ref<any[]>([])
const currentImageCategory = ref('检验报告') // 新增：用于保存当前图片类型

// 上传配置
const uploadHeaders = imageService.getUploadHeaders()

// 获取多图片上传URL
const getMultipleUploadUrl = computed(() => {
    if (!detailData.value || !detailData.value.productionBatch) {
        return imageService.getMultipleUploadUrl('traceability2212b')
    }
    // 使用批次编号和当前图片类型
    return `${imageService.getMultipleUploadUrl('traceability2212b')}&productionBatch=${encodeURIComponent(detailData.value.productionBatch)}&imageCategory=${encodeURIComponent(currentImageCategory.value)}`
})

const beforeUpload = (rawFile: File) => {
    const isJPGOrPNG = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png'
    const isLt5M = rawFile.size / 1024 / 1024 < 5
    if (!isJPGOrPNG) {
        ElMessage.error('图片只能是 JPG/PNG 格式!')
    }
    if (!isLt5M) {
        ElMessage.error('图片大小不能超过 5MB!')
    }
    return isJPGOrPNG && isLt5M
}
const handleUploadSuccess = (response: any, file: any, fileList: any[]) => {
    if (response.success) {
        // 处理单个图片上传成功的情况
        if (response.data) {
            const newImage = {
                url: response.data.imageUrl || response.data.url,
                uid: file.uid
            }
            inspectionImages.value.push(newImage)
        }
        // 处理多个图片上传成功的情况
        else if (Array.isArray(response.data)) {
            response.data.forEach((item: any) => {
                const newImage = {
                    url: item.imageUrl || item.url,
                    uid: `${file.uid}_${inspectionImages.value.length}`
                }
                inspectionImages.value.push(newImage)
            })
        }
        ElMessage.success('图片上传成功')
    } else {
        ElMessage.error(response.message || '图片上传失败')
    }
}
const handleUploadError = (err: any, file: any, fileList: any[]) => {
    ElMessage.error('图片上传失败，请稍后再试')
}

const handleExceed = (files: any, uploadFiles: any) => {
    ElMessage.warning(`最多只能上传 10 张图片，您选择了 ${files.length} 张`)
}

const confirmUpload = () => {
    uploadDialogVisible.value = false
    // 如果有详情数据，刷新产品检验报告图片
    if (detailData.value && detailData.value.productionBatch) {
        fetchInspectionImages(detailData.value.productionBatch)
    }
    ElMessage.success('图片上传成功')
}

const deleteImage = async (image: { uid: string, url: string }) => {
    try {
        // 使用图片主键编号删除
        const response = await imageService.deleteImage(image.uid);
        if (response.success) {
            // 从列表中移除
            inspectionImages.value = inspectionImages.value.filter(item => item.uid !== image.uid);
            ElMessage.success('图片删除成功');
        } else {
            ElMessage.error(response.message || '图片删除失败');
        }
    } catch (error) {
        console.error('删除图片失败:', error);
        ElMessage.error('删除图片失败，请稍后再试');
    }
}

// 显示上传对话框
const showUploadDialog = (imageCategory: string = '检验报告') => {
    fileList.value = [] // 清空文件列表
    currentImageCategory.value = imageCategory // 保存当前图片类型
    uploadDialogVisible.value = true
}

// 获取详情数据
const fetchDetail = async () => {
    const id = route.params.id
    if (!id) {
        ElMessage.error('溯源编号不存在')
        router.push('/menu/traceability')
        return
    }
    loading.value = true
    try {
        const response = await traceabilityService.getTraceabilityInfoById(id as string)
        if (response.success && response.data) {
            detailData.value = response.data
            // 获取产品检验报告图片
            fetchInspectionImages(response.data.productionBatch)
        } else {
            ElMessage.error(response.message || '获取溯源信息详情失败')
        }
    } catch (error) {
        console.error('获取溯源信息详情失败:', error)
        ElMessage.error('获取溯源信息详情失败，请稍后再试')
    } finally {
        loading.value = false
    }
}
// 获取产品检验报告图片
const fetchInspectionImages = async (productionBatch: string) => {
    if (!productionBatch) return
    try {
        const response = await imageService.queryImages({
            ImageCategory: currentImageCategory.value, // 使用当前图片类型
            ProductionBatch: productionBatch
        })
        if (response.success && response.data) {
            inspectionImages.value = response.data.map(img => ({
                url: img.imageUrl,
                uid: img.imageId
            }))
        }
    } catch (error) {
        console.error('获取产品检验报告图片失败:', error)
        ElMessage.error('获取产品检验报告图片失败，请稍后再试')
    }
}

// 返回列表页
const goBack = () => {
    router.push('/menu/traceability')
}

onMounted(() => {
    fetchDetail()
})
</script>

<style scoped>
.detail-container {
    padding: 20px;
}

.content-header {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content-title {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    gap: 15px;
}

.loading-container,
.error-container {
    padding: 30px;
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.detail-content {
    background-color: #f5f7fa;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 20px;
}

.detail-section {
    margin-bottom: 20px;
    background-color: white;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.product-layout {
    display: flex;
    gap: 30px;
    margin-bottom: 20px;
}

.product-image-container {
    flex: 0 0 180px;
}

.product-info-container {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.product-details {
    margin-bottom: 20px;
}

.detail-section h2 {
    font-size: 22px;
    margin-bottom: 20px;
    color: #333;
}

.product-image {
    width: 180px;
    height: 180px;
    overflow: hidden;
    border-radius: 4px;
    border: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-details {
    flex: 1;
}

.info-row {
    margin-bottom: 15px;
    display: flex;
}

.info-label {
    width: 120px;
    color: #666;
    font-weight: bold;
}

.info-value {
    color: #333;
}

.detail-tabs {
    margin-top: 20px;
}

.batch-info {
    display: flex;
    align-items: center;
    background-color: #f0f9eb;
    padding: 5px 10px;
    border-radius: 4px;
    font-size: 14px;
}

.batch-label {
    font-weight: bold;
    margin-right: 5px;
    color: #67c23a;
}

.batch-value {
    color: #606266;
}

.upload-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px 0;
}

.el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 10px;
    text-align: center;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.report-section {
    margin-top: 20px;
    border-top: 1px solid #ebeef5;
    padding-top: 15px;
}

.report-title {
    font-size: 16px;
    margin-bottom: 15px;
    color: #333;
    font-weight: 500;
    position: relative;
    display: flex;
    align-items: center;
}

.report-content {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
}
</style>